import React, { useRef, useState, useEffect } from 'react';
import { Form, Input, Button, message } from 'antd';
const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
};
function AddAttrForm({ info, currentAttr, onDispatch, onClose }){
    const inputRef = useRef();
    useEffect(()=>{
        if ( inputRef.current && inputRef.current.focus ) {
            inputRef.current.focus();
        }
    },[])
    return (
        <Form 
            name="add_field_attr" 
            {...layout}  
            initialValues={{ attrName:info.forEdit ? currentAttr.attrName : ''  }}
            onFinish={(values)=>{            
                new Promise((resolve, reject)=>{
                    if ( info.forEdit ) {
                        onDispatch({ type:'fields/updateAttrAsync', payload:{ resolve, reject, fieldAttrId:currentAttr.attrId, fieldAttrName:values.attrName }})
                    } else {
                        onDispatch({type:'fields/addAttrAsync', payload:{ isChild:info.isChild, attrName:values.attrName, resolve, reject }})
                    }
                })
                .then(()=>{
                    message.success(  ( info.forEdit ? '更新' : '添加' ) +  '属性成功');
                    onClose();
                })
                .catch(msg=>message.error(msg))               
            }}
        >
            <Form.Item name="attrName" label="维度属性" rules={[{required:true, message:'维度属性不能为空!'}]}>
                <Input ref={inputRef} />
            </Form.Item>
            <Form.Item wrapperCol={{...layout.wrapperCol, offset:6 }}>
                <Button type="primary" htmlType="submit" style={{ marginRight:'1rem' }}>确定</Button>
                <Button onClick={()=>onClose()}>取消</Button>
            </Form.Item>
        </Form>
    )
}


export default React.memo(AddAttrForm);